package br.com.dataphonebr.schedule;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import android.app.IntentService;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.media.RingtoneManager;
import android.net.Uri;
import android.preference.PreferenceManager;
import android.support.v4.app.NotificationCompat;
import br.com.dataphonebr.NotificationViewActivity;
import br.com.dataphonebr.R;
import br.com.dataphonebr.entity.Atividade;
import br.com.dataphonebr.service.AtividadeService;
import br.com.dataphonebr.util.AlarmUtil;
import br.com.dataphonebr.util.AlarmVO;
import br.com.dataphonebr.util.Util;

/**
 * This {@code IntentService} does the app's actual work.
 * {@code SampleAlarmReceiver} (a {@code WakefulBroadcastReceiver}) holds a
 * partial wake lock for this service while the service does its work. When the
 * service is finished, it calls {@code completeWakefulIntent()} to release the
 * wake lock.
 */
public class SampleSchedulingService extends IntentService {
    public SampleSchedulingService() {
        super("SchedulingService");
    }
    
    public static final String TAG = "Scheduling Demo";
    // An ID used to post the notification.
    public static final int NOTIFICATION_ID = 1;
    public static final String SEARCH_STRING = "doodle";
    public static final String URL = "http://www.google.com";
    private AlarmUtil alarmUtil;
    private Util util = new Util();
    private NotificationManager mNotificationManager;
    NotificationCompat.Builder builder;
    private AtividadeService atividadeService;
    private SampleAlarmReceiver sampleAlarmReceiver = new SampleAlarmReceiver();;

    @Override
    protected void onHandleIntent(Intent intent) {
    	atividadeService = new AtividadeService(getApplicationContext());
    	alarmUtil = new AlarmUtil(getApplicationContext());
        Integer requestCode = intent.getExtras().getInt("requestCode");
        if (requestCode != null){
        	AlarmVO currentAlarm = alarmUtil.getAlarmByRequestCode(requestCode);
        	if (currentAlarm != null && currentAlarm.getId() != null){
        		if (currentAlarm.getId() == AlarmUtil.ID_UPDATE){
        			alarmUtil.addTodayListToAlarm(atividadeService.selectAtividadesNotificaveis());
//        			apenas para testes
//        			Atividade atividadeTemp = new Atividade();
//        			atividadeTemp.setDescricao("Atividades sendo atualizadas");
//        			atividadeTemp.setDescricao("processamento automatico");
//        			sendNotification(atividadeTemp);
        			sampleAlarmReceiver.setAlarm(getApplicationContext());
        			return;
        		} else {
        			Atividade atividade = atividadeService.selectById(currentAlarm.getId());
        			if (atividade != null){
        				List<AlarmVO> alarms = new ArrayList<AlarmVO>();
        				currentAlarm.setSent(true);
        				alarms.add(currentAlarm);
        				alarmUtil.addToSentList(alarms);
        				sampleAlarmReceiver.removeAlarm(alarms, getApplicationContext());
        				sendNotification(atividade);
        			}
        		}
        	}
        }
        // Release the wake lock provided by the BroadcastReceiver.
        SampleAlarmReceiver.completeWakefulIntent(intent);
        // END_INCLUDE(service_onhandle)
    }
    
    // Post a notification indicating whether a doodle was found.
    private void sendNotification(Atividade atividade) {
    	boolean tipoAlarme = atividade != null && atividade.getTipoNotificacaoAlarme() != null && atividade.getTipoNotificacaoAlarme()?true:false;
        mNotificationManager = (NotificationManager)this.getSystemService(Context.NOTIFICATION_SERVICE);
		Intent intent = new Intent(this, NotificationViewActivity.class);
		intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		intent.putExtra(new AtividadeService(getApplicationContext()).getColumnHack(), atividade.getCodigo());
		StringBuffer subtitulo  = new StringBuffer();
		String titulo = atividade.getTitulo();
		Date horaInicio = atividade.getHoraAviso();
//        if (horaInicio != null){
//        	if (util.time1IsHigherThanTime2(atividade.getHoraAviso(), atividade.getHoraIni()))
//        		horaInicio = atividade.getHoraAviso();
//        }
        subtitulo.append("Marcado para ").append(util.timeToString(horaInicio));
        titulo = atividade.getTitulo();
		intent.putExtra("_fromNotification", true);
        PendingIntent contentIntent = PendingIntent.getActivity(this, 0, intent, Intent.FLAG_ACTIVITY_NEW_TASK);

        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
        .setSmallIcon(R.drawable.ic_launcher)
        .setUsesChronometer(true)
        .setContentTitle(titulo)
        .setStyle(new NotificationCompat.BigTextStyle()
        .bigText(subtitulo.toString()))
        .setTicker(atividade.getTitulo())
        .setUsesChronometer(true)
        .setAutoCancel(true);
        
        if (tipoAlarme)
        	mBuilder.setFullScreenIntent(contentIntent, true);
        else
        	mBuilder.setContentIntent(contentIntent);
        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
        Boolean notify = preferences.getBoolean("notifications_new_message", true);
        String ringtone = null;
        Uri uri = null;
        if (notify){
	        try {
	        	ringtone = preferences.getString("notifications_new_message_ringtone", "");
		       	if (ringtone != null && !ringtone.isEmpty()){
		       		uri = Uri.parse(ringtone);
		       	} else {
		       		uri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
		       	}
		       	mBuilder.setSound(uri);        
	        } catch (Exception e){
	        	e.printStackTrace();
	        	System.out.println("ERRO NO SOM DA MENSAGEM :"+e.getMessage());
	        }
        }
       	mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
       	if (tipoAlarme)
       		mNotificationManager.cancel(NOTIFICATION_ID);
    }
 
//
// The methods below this line fetch content from the specified URL and return the
// content as a string.
//
    /** Given a URL string, initiate a fetch operation. */
    private String loadFromNetwork(String urlString) throws IOException {
        InputStream stream = null;
        String str ="";
      
        try {
            stream = downloadUrl(urlString);
            str = readIt(stream);
        } finally {
            if (stream != null) {
                stream.close();
            }      
        }
        return str;
    }

    /**
     * Given a string representation of a URL, sets up a connection and gets
     * an input stream.
     * @param urlString A string representation of a URL.
     * @return An InputStream retrieved from a successful HttpURLConnection.
     * @throws IOException
     */
    private InputStream downloadUrl(String urlString) throws IOException {
    
        URL url = new URL(urlString);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setReadTimeout(10000 /* milliseconds */);
        conn.setConnectTimeout(15000 /* milliseconds */);
        conn.setRequestMethod("GET");
        conn.setDoInput(true);
        // Start the query
        conn.connect();
        InputStream stream = conn.getInputStream();
        return stream;
    }

    /** 
     * Reads an InputStream and converts it to a String.
     * @param stream InputStream containing HTML from www.google.com.
     * @return String version of InputStream.
     * @throws IOException
     */
    private String readIt(InputStream stream) throws IOException {
      
        StringBuilder builder = new StringBuilder();
        BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
        for(String line = reader.readLine(); line != null; line = reader.readLine()) 
            builder.append(line);
        reader.close();
        return builder.toString();
    }
}
